package com.weaver.drools.dao.factory;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import com.weaver.drools.dao.common.impl.CommonBaseDaoImpl;

import javax.persistence.EntityManager;
import java.io.Serializable;
/**
 * 
 *  @application name:
 *  @author: zhouxinlei 
 *  @time：2018年6月27日
 *  @version：ver 1.1
 */
public class CommonBaseDaoFactoryBean<R extends JpaRepository<T, I>, T,I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {
	
    public CommonBaseDaoFactoryBean(Class<? extends R> repositoryInterface) {
		super(repositoryInterface);
		// TODO Auto-generated constructor stub
	}

	
    @SuppressWarnings("rawtypes")
	protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new CommonBaseDaoFactory(em);
    }

    //创建一个内部类，该类不用在外部访问
    private static class CommonBaseDaoFactory<T, I extends Serializable,R>
            extends JpaRepositoryFactory {

        private final EntityManager entityManager;

        public CommonBaseDaoFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        //设置具体的实现类是BaseRepositoryImple
        
        @SuppressWarnings("unchecked")
		protected Object getTargetRepository(RepositoryInformation information) {
            return new CommonBaseDaoImpl<T, I>((Class<T>) information.getDomainType(), entityManager);
        }

        //设置具体的实现类的class
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return CommonBaseDaoImpl.class;
        }
    }
}
